import { useUserStore } from '@/stores/user'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  // hash模式：createWebHashHistory() --> 带 '#' 的
  // history模式：createWebHistory()

  // import.meta.env.BASE_URL --> vite.config.js 中的 base 配置项
  //  给所有路径前加的内容
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import("@/views/login/LoginPage.vue") },
    {
      path: '/',
      component: () => import("@/views/layout/LayoutContainer.vue"),
      redirect: '/article/manage',
      children: [
        {
          path: '/article/manage',
          component: () => import('@/views/article/ArticleManage.vue')
        },
        {
          path: '/article/channel',
          component: () => import('@/views/article/ArticleChannel.vue')
        },
        {
          path: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue')
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue')
        },
        {
          path: '/user/password',
          component: () => import('@/views/user/UserPassword.vue')
        },

      ]
    }
  ],
})

// 没有return、true --> 都放行
// 返回false --> 回到原地址
// 返回指定地址 --> 跳转到指定地址，这里跳转到登录
router.beforeEach((to, form) => {
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/login') return '/login'
})

export default router
